var conn, isSending = false, loginOptions = null;

WebIM.action = {
	login: function(options){
		loginOptions = options;
		WebIM.utils.context = {accessToken:options.accessToken};
		conn.open({
			apiUrl: WebIM.config.apiURL,
			user: options.username,
			pwd: options.password,
			accessToken : options.accessToken,
			appKey: WebIM.config.appkey
		});
	},
	register: function(options){
		WebIM.utils.registerUser({
			apiUrl: WebIM.config.apiURL,
			username: options.username,
			password: options.password,
			nickname: options.nickname,
			appKey: WebIM.config.appkey,
			success: function(){
				WebIM.action.login(options);
			},
			error: function(){ }
		});
	},
	logout: function(){
		conn.close();
	},
	opened: function(message){
		!WebIM.config.isAutoLogin && conn.setPresence();
		if($.isPlainObject(loginOptions) && $.isFunction(loginOptions.callback))loginOptions.callback.call(conn, message.accessToken);
		loginOptions = null;
	},
	error: function(e){
		if (e.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_CLOSE_ERROR) {
			if (e.msg == '' || e.msg == 'unknown') {
				$.overloadError('服务器断开连接,可能是账号在别处登录');
			}
		} else if (e.type === WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
			if (e.msg.toLowerCase().indexOf('user removed') != -1) {
				$.overloadError('该账号已被删除');
			}
		} else if (e.type === WebIM.statusCode.WEBIM_CONNCTION_OPEN_USERGRID_ERROR) {
			//登录失败
			if($.isPlainObject(loginOptions))WebIM.action.register(loginOptions);
			loginOptions = null;
		} else if (e.type === WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
			conn.clear();
			conn.close();
		}
		//console.log(e);
	},
	uploadFile: function(fileInputId, options){
		if(fileInputId instanceof jQuery)fileInputId = fileInputId[0];
		var fileInfo = WebIM.utils.getFileUrl(fileInputId);
		var opt = {
			apiUrl: WebIM.config.apiURL,
			file: fileInfo,
			onFileUploadComplete: options.complete, //一个参数json
			onFileUploadError: options.error //一个参数e
		};
		WebIM.utils.uploadFile.call(conn, opt);
	},
	downloadFile: function(options){
		var devInfos = WebIM.config.appkey.split('#'), orgName = devInfos[0], appName = devInfos[1];
		var opt = {
			mimeType: options.mimeType ? options.mimeType+'; charset=x-user-defined' : '',
			url: options.url,
			secret: options.secret,
			onFileDownloadComplete: function(response){ //一个参数src
				if($.isFunction(options.complete)){
					var blob = new Blob(); 
					blob = response;
					var src = window.URL.createObjectURL(blob);
					options.complete(src);
				}
			},
			onFileDownloadError: options.error
		};
		if (options.headers) opt.headers = options.headers;
		WebIM.utils.download.call(conn, opt);
	},
	getFileUrl: function(fileInputId, callback){
		var file = WebIM.utils.getFileUrl(fileInputId);
		var fileObj = {data:file.data, url:file.url, filename:file.filename, filesize:file.filesize, filetype:file.filetype};
		var fileType = ['jpg', 'jpeg', 'gif', 'png', 'bmp'];
		if($.inArray(file.filetype.toLowerCase(), fileType)<0){
			if($.isFunction(callback))callback.call(file, fileObj);
			return;
		};
		var img = new Image();
		img.src = file.url;
		var check = function(){
			if(img.width>0 || img.height>0){
				clearInterval(set);
				fileObj.size = {width:img.width, height:img.height};
				if($.isFunction(callback))callback.call(fileObj);
			}
		};
		var set = setInterval(check, 40);
		return file;
	},
	//发送消息
	sendMessage: function(options){
		if (isSending) return;
		isSending = true;
		var id = conn.getUniqueId();//生成本地消息id
		var msg = new WebIM.message(options.msgType, id);//创建文本消息
		options = $.extend(options, {
			to: options.to,
			ext: options.ext ? options.ext : '',
			success: function(id, serverMsgId){
				$.overload(false);
				isSending = false;
				var _this = this, bodies = {type:options.msgType};
				switch(options.msgType){
					case 'txt':
						bodies = $.extend(bodies, {
							msg: options.msg
						});
						break;
					case 'loc':
						bodies = $.extend(bodies, {
							addr: options.address,
							lat: options.lat,
							lng: options.lng
						});
						break;
					case 'cmd':
						bodies = $.extend(bodies, {
							msg: options.msg,
							action: options.action
						});
						break;
					case 'img': case 'audio': case 'video': case 'file':
						bodies = $.extend(bodies, {
							url: this.msg.body.url,
							secret: this.msg.body.secret,
							filename: this.msg.file.filename,
							file_length: this.msg.file.filesize
						});
						switch(options.msgType){
							case 'img':
								bodies = $.extend(bodies, {
									size: options.size
								});
								break;
							case 'audio':
								bodies = $.extend(bodies, {
									length: 0
								});
								break;
							case 'video':
								bodies = $.extend(bodies, {
									length: 0,
									thumb: '',
									thumb_secret: ''
								});
								break;
						}
						break;
				};
				var payload = {ext:options.ext, bodies:[bodies]};
				if($.isFunction(options.sendComplete))options.sendComplete.call(conn, serverMsgId, payload);
			},
			fail: function(e){
				$.overload(false);
				isSending = false;
				if($.isFunction(options.sendError))options.sendError.call(conn, e);
			}
		});
		msg.set(options);
		if (options.chatType=='group') { 
			msg.setGroup('groupchat');
		} else if (options.chatType=='room') {
			msg.body.roomType = true;
			msg.setGroup('groupchat');
		};
		conn.send(msg.body);
	},
	sendAttachmentMessage: function(options){//发送附件消息,例如发送图片消息
		if($.isArray(options.fileType) && $.inArray(options.file.filetype.toLowerCase(), options.fileType)<0){
			$.overloadError('文件类型不允许');
			return;
		};
		options = $.extend(options, {
			apiUrl: WebIM.config.apiURL,
			file: options.file,
			onFileUploadComplete: function(data){
				//文件地址：data.uri + '/' + data.entities[0].uuid;
				if($.isFunction(options.uploadComplete))options.uploadComplete.call(conn, data);
			},
			onFileUploadError: function(error){
				if($.isFunction(options.uploadError))options.uploadError.call(conn, error);
				else $.overloadError(error);
			},
			flashUpload: WebIM.flashUpload
		});
		$.overload(null);
		this.sendMessage(options);
	},
	sendText: function(options){
		if(!options.msg.length){$.overloadError('请输入聊天内容');return}
		options = $.extend(options, {
			msgType: 'txt',
			msg: options.msg
		});
		this.sendMessage(options);
	},
	sendEmoji: function(options){
		
	},
	sendImage: function(options){
		var _this = this, file = WebIM.utils.getFileUrl(options.input);
		if(file.url==null || file.url==''){$.overloadError('请选择文件');return};
		WebIM.action.getFileUrl(options.input, function(){
			options = $.extend(options, {
				msgType: 'img',
				file: file,
				fileType: ['jpg', 'jpeg', 'gif', 'png', 'bmp'],
				size: this.size
			});
			_this.sendAttachmentMessage(options);
		});
	},
	sendLocation: function(options){
		if(!options.lat || !options.lng){$.overloadError('请设置经纬度值');return};
		options = $.extend(options, {
			msgType: 'loc',
			addr: options.address,
			lat: options.lat,
			lng: options.lng
		});
		this.sendMessage(options);
	},
	sendAudio: function(options){
		var file = WebIM.utils.getFileUrl(options.input);
		var size = WebIM.utils.getFileSize(options.input);
		if(file.url==null || file.url==''){$.overloadError('请选择文件');return};
		options = $.extend(options, {
			msgType: 'audio',
			file: file,
			fileType: ['amr', 'mp3'],
			length: options.length,
			file_length: size
		});
		this.sendAttachmentMessage(options);
	},
	sendVideo: function(options){
		var file = WebIM.utils.getFileUrl(options.input);
		var size = WebIM.utils.getFileSize(options.input);
		if(file.url==null || file.url==''){$.overloadError('请选择文件');return};
		options = $.extend(options, {
			msgType: 'video',
			file: file,
			fileType: ['mp4'],
			length: options.length,
			file_length: size
		});
		this.sendAttachmentMessage(options);
	},
	sendFile: function(options){
		var file = WebIM.utils.getFileUrl(options.input);
		if(file.url==null || file.url==''){$.overloadError('请选择文件');return};
		options = $.extend(options, {
			msgType: 'file',
			file: file,
			filename: options.filename
		});
		this.sendAttachmentMessage(options);
	},
	sendCmd: function(options){
		if(!options.action.length){console.log('请输入聊天内容');return}
		options = $.extend(options, {
			msgType: 'cmd',
			msg: 'cmd',
			action: options.action//cmd命令
		});
		this.sendMessage(options);
	},
	//接收消息, override
	receiveText: function(message){ },
	receiveEmoji: function(message){ },
	receiveImage: function(message){ },
	receiveLocation: function(message){ },
	receiveAudio: function(message){ },
	receiveVideo: function(message){ },
	receiveFile: function(message){ },
	receiveCmd: function(message){ }
};

conn = new WebIM.connection({
	https: WebIM.config.https,
	url: WebIM.config.xmppURL,
	isAutoLogin: WebIM.config.isAutoLogin,
	isMultiLoginSessions: WebIM.config.isMultiLoginSessions
});
conn.listen({
	onOpened: function(message){WebIM.action.opened(message)},//连接成功回调
	onClosed: function(message){},//连接关闭回调
	onPresence: function(message){},//收到联系人订阅请求、处理群组、聊天室被踢解散等消息
	onRoster: function(message){},//处理好友申请
	onInviteMessage: function(message){},//处理群组邀请
	onOnline: function(){},//本机网络连接成功
	onOffline: function(){},//本机网络掉线
	onError: function(message){WebIM.action.error(message)},//失败回调
	onTextMessage: function(message){WebIM.action.receiveText(message)},//收到文本消息
	onEmojiMessage: function(message){WebIM.action.receiveEmoji(message)},//收到表情消息
	onPictureMessage: function(message){WebIM.action.receiveImage(message)},//收到图片消息
	onLocationMessage: function(message){WebIM.action.receiveLocation(message)},//收到位置消息
	onAudioMessage: function(message){WebIM.action.receiveAudio(message)},//收到音频消息
	onVideoMessage: function(message){WebIM.action.receiveVideo(message)},//收到视频消息
	onFileMessage: function(message){WebIM.action.receiveFile(message)},//收到文件消息
	onCmdMessage: function(message){WebIM.action.receiveCmd(message)}//收到命令消息
});
